﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace daStaticAnalyser.Analysers
{
    using daStaticAnalyser;
    using daBase.Objects;
    using daBase.Analyser;
    using daSyntaxAnalyser;
    using daSyntaxAnalyser.SyntaxTree;

    [AnalyserDefaultSettings("Метрика Мак-Клура", "test", 0, "test")]
    class MacKlurAnalyzer : BaseStaticAnalyser
    {
        List<MethodInf> Funcs = new List<MethodInf>();

        void GetData(ISyntaxTreeElement e, MethodInf owner)
        {
            if (e == null) return;

            if (//(e is VariableStatementElement) ||
                (e is StandartVariableExpressionElement))
            {
                String temp = e.ToString();
                if (temp.Contains("("))
                {
                    int pos = temp.IndexOf('(');
                    String temp2 = temp.Substring(0, pos);

                    if (!owner.gp.Contains(temp2)) owner.gp.Add(temp2);
                    owner.yp++;

                    MethodInf Func = Funcs.Find(s => s.Name == temp2);
                    if (Func == null)
                    {
                        Funcs.Add(new MethodInf(temp2, owner.Name));
                    }
                    else
                    {
                        if (!Func.fp.Contains(owner.Name)) Func.fp.Add(owner.Name);
                        Func.xp++;
                    }
                }
            }

            foreach (var elt in e) GetData(elt, owner);
        }

        protected override void DoAnalyse(SyntaxTreeArgs e)
        {
            String MethodName = "";
            if (CheckMethod_GetName(e, out MethodName))
            {
                OuterMethodElement Method = e.Element as OuterMethodElement;
                MethodInf Func = Funcs.Find(s => s.Name == MethodName);
                if(Func==null)
                    Funcs.Add(new MethodInf(MethodName, Method.StartInfo.File, Method.StartInfo.Line));
                GetData(Method.Body.Statement, Funcs[Funcs.Count-1]);
            }
        }

        protected override void DoFinishAnalyse(EventArgs e)
        { 
            foreach(var Func in Funcs)
            {
                int M = Func.fp.Count * Func.xp + Func.gp.Count * Func.yp;
                AddMetric("Метрика Мак-Клура", M,
                    Func.Name,
                    Func.File,
                    Func.Line);
            }
            Funcs.Clear();
        }
    }
}
